package top.kikt.book.core.handlers.common

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.base.BookChapterHandler
import top.kikt.book.core.base.BookHandler
import top.kikt.book.core.base.BookMetaHandler
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity

abstract class BasePagingBookHandler : BookHandler, BookHandlerContext(), ContentPagingHandler {

    override fun createBookMetaHandler(): BookMetaHandler {
        return this
    }

    override fun createBookChapterHandler(): BookChapterHandler {
        return this
    }

    override fun isSupported(): Boolean {
        return true
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = ArrayList<ChapterMetaEntity>()

        var page = 1

        var doc = document
        var newMenuUrl = menuUrl

        while (true) {
            println("请求第 $page 页的目录: $newMenuUrl")
            val newEntity = parsePagingChapterMeta(doc, newMenuUrl)
            result.addAll(newEntity.map {
                it.copy(index = result.size + it.index)
            })
            val nextPageUrl = nextMenuPageUrl(doc, newMenuUrl) ?: break
            newMenuUrl = nextPageUrl
            doc = nextPageUrl.toHttpUrl().toDocument() ?: throw Exception("Get next page failed")
            page++
        }

        for (chapterMetaEntity in result) {
            println("${chapterMetaEntity.index} ${chapterMetaEntity.name} ${chapterMetaEntity.url}")
        }

        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        return handleChapter(chapterMetaEntity)
    }

    abstract fun nextMenuPageUrl(document: Document, newMenuUrl: String): String?

    abstract fun parsePagingChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity>

    override fun searchBook(keyword: String): List<String> {
        return emptyList()
    }

}